package com.biz.primus.ms.oms.service.allocation.validator;

import com.biz.primus.model.oms.enums.OrderDeliveryType;
import com.biz.primus.model.oms.enums.OrderInterceptPropertyName;
import com.biz.primus.model.oms.enums.OrderInterceptType;
import com.biz.primus.model.oms.vo.OrderInterceptVo;
import com.biz.primus.ms.oms.dao.po.OmsOrder;
import com.biz.primus.ms.oms.dao.po.OmsOrderItem;
import com.biz.primus.ms.oms.dao.po.OrderIntercept;
import com.biz.primus.ms.oms.dao.repository.OrderInterceptRepository;
import com.biz.primus.ms.oms.service.core.OrderInterceptService;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 用户定义的拦截规则
 * @author LGJ
 * @date  2017/11/24
 */
@Component
public class UserDefinedValidator implements OrderValidator{

	@Autowired
	private OrderInterceptService orderInterceptService;


	@Override
	public VerificationResult validate(OmsOrder order) {
		//查询出启用的拦截规则
		List<OrderInterceptType> orderInterceptTypes = Lists.newArrayList();
		orderInterceptTypes.add(OrderInterceptType.all);
		if(order.getDeliveryType()== OrderDeliveryType.self_now){
			orderInterceptTypes.add(OrderInterceptType.now);
		}
		if(order.getDeliveryType()== OrderDeliveryType.self_normal){
			orderInterceptTypes.add(OrderInterceptType.normal);
		}
		if(order.getDeliveryType()== OrderDeliveryType.self_appointment){
			orderInterceptTypes.add(OrderInterceptType.appointment);
		}
		List<OrderInterceptVo> orderInterceptVos = orderInterceptService.findByStateAndType(orderInterceptTypes);

		for(OrderInterceptVo orderInterceptVo:orderInterceptVos){
			if(orderInterceptVo.getPropertyName()==OrderInterceptPropertyName.order_amount){
				Integer orderAmount = Integer.valueOf(orderInterceptVo.getPropertyValue());
				if(order.getOrderAmount()>=orderAmount){
					return new VerificationResult(true,"订单金额满足拦截规则,被拦截,无法自动分单!");
				}
			}

			if(orderInterceptVo.getPropertyName()==OrderInterceptPropertyName.product_code){
				for(OmsOrderItem omsOrderItem:order.getItems()){
					if(Objects.equals(omsOrderItem.getProductCode(),orderInterceptVo.getPropertyValue())){
						return new VerificationResult(true,"订单商品编码满足拦截规则,被拦截,无法自动分单!");
					}
				}
			}
		}
		return new VerificationResult(false,null);
	}

	@Override
	public String getValidatorName() {
		return "userDefined";
	}
}
